package com.bcgtgjyb.huanwen.customview.mylibrary;

import ohos.agp.animation.Animator;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

/**
 * Created by bigwen on 2015/12/31.
 */
public class SquareLine extends Component implements Component.DrawTask {
    float mF = 0;
    private Paint paint;
    private DataAnimatorValue valueA;
    private int delayTime = 500;
    private boolean isInitView = false;
    private EventHandler eventHandler = new EventHandler(EventRunner.getMainEventRunner());

    /**
     * 构造
     *
     * @param context 上下文
     */
    public SquareLine(Context context) {
        super(context);
        init();
    }

    /**
     * 构造
     *
     * @param context 上下文
     * @param attrs 属性集
     */
    public SquareLine(Context context, AttrSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        addDrawTask(this::onDraw);
        paint = new Paint();
        paint.setColor(new Color(Color.getIntColor("#259b24")));
        paint.setStrokeWidth(10);
    }

    private void start() {
        if (valueA == null) {
            valueA = getValueAnimator();
        } else {
            valueA.start();
        }
        invalidate();
        eventHandler.postTask(new Runnable() {
            @Override
            public void run() {
                start();
                invalidate();
            }
        }, 10);
    }

    private DataAnimatorValue getValueAnimator() {
        DataAnimatorValue valueAnimator = new DataAnimatorValue();
        valueAnimator.setStart(0);
        valueAnimator.setEnd(1);
        valueAnimator.setDuration(delayTime);
        valueAnimator.setCurveType(Animator.CurveType.LINEAR);
        valueAnimator.start();
        invalidate();
        return valueAnimator;
    }

    private float yValue(float xx, int length) {
        float allLength = getEstimatedWidth();
        return allLength / 1 * xx;
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        if (!isInitView) {
            start();
            isInitView = true;
        }
        int height = getEstimatedHeight();
        int width = getEstimatedWidth();
        int length = width / 9;

        if (valueA.isRunning()) {
            mF = (float) valueA.getAnimatedValue();
        }
        canvas.drawLines(new float[]{yValue(mF, length), (float) ((double)height / 2), length * 4 + yValue(mF, length), (float) ((double)height / 2)}, paint);
        canvas.drawLines(new float[]{yValue(mF, length) - width, (float) ((double)height / 2), length * 4 + yValue(mF, length) - width, (float) ((double)height / 2)}, paint);
    }
}
